package me.sealer.ssm.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import me.sealer.ssm.constant.Dict;
import me.sealer.ssm.constant.RoleConstant;
import me.sealer.ssm.controller.dto.CommonResponse;
import me.sealer.ssm.controller.dto.QueryMenusResponse;
import me.sealer.ssm.controller.dto.RoleMenusModifyRequest;
import me.sealer.ssm.model.Menu;
import me.sealer.ssm.service.MenuService;
import me.sealer.ssm.service.RoleMenuService;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author sealer
 * @date 2016/09/27
 */
@Slf4j
@RestController
@Api(tags = "角色菜单管理相关api")
@RequestMapping("/roleMenuMgmt")
@RequiresRoles(value = {RoleConstant.ROLE_ADMIN})
public class RoleMenuMgmtController {
    private final MenuService menuService;
    private final RoleMenuService roleMenuService;

    public RoleMenuMgmtController(MenuService menuService, RoleMenuService roleMenuService) {
        this.menuService = menuService;
        this.roleMenuService = roleMenuService;
    }

    @GetMapping("/menu/{roleName}")
    @ApiOperation(value = "查询角色对应的所有(一级)菜单")
    public CommonResponse<QueryMenusResponse> queryMenus(@ApiParam(value = "角色名", required = true) @PathVariable(value = Dict.ROLE_NAME) String roleName) {

        // having menus
        List<Menu> havingMenus = roleMenuService.queryMenusByRoleName(roleName);
        List<Integer> havingMenusIds = havingMenus.stream().map(Menu::getId).collect(Collectors.toList());

        // all menus
        List<Menu> allMenus = menuService.queryFirstMenus();
        return new CommonResponse<>(new QueryMenusResponse(roleName, havingMenusIds, allMenus));
    }

    @ApiOperation(value = "修改角色菜单")
    @PostMapping(value = "/modify", produces = MediaType.APPLICATION_JSON_VALUE)
    public CommonResponse modify(@Valid @RequestBody RoleMenusModifyRequest roleMenusModifyRequest) {

        String roleName = roleMenusModifyRequest.getRoleName();
        List<Integer> menus = roleMenusModifyRequest.getMenus();
        roleMenuService.modifyRoleMenus(roleName, menus);
        return new CommonResponse();
    }
}
